<template>
  <!-- <cjui-mouse-box :event="eventName"></cjui-mouse-box> -->
  <div ref="cjuiMouseBox" class="cjui-mouse-box">
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { ref, watch } from 'vue';

export default {
  name: 'CjuiMouseBox',
  props: {
    event: {  // 传入鼠标点击事件
      type: Object,
      default: () => ({})
    },
    margin: {  // 边界安全距离
      type: Number,
      default: 10,
    },
  },
  setup(props: any) {
    const cjuiMouseBox = ref();

    function closeEvent() {
      document.removeEventListener('click', closeEvent);
      cjuiMouseBox.value.style.display = 'none';
    }
    function init() {
      // Get window size:
      const winWidth = document.body.clientWidth;
      const winHeight = document.body.clientHeight;

      // Get contextmenu size:
      cjuiMouseBox.value.style.opacity = 0;
      cjuiMouseBox.value.style.display = 'block';
      const menuWidth = parseInt(window.getComputedStyle(cjuiMouseBox.value).getPropertyValue('width'));
      const menuHeight = parseInt(window.getComputedStyle(cjuiMouseBox.value).getPropertyValue('height'));

      // Get pointer position:
      const posX = props.event.pageX;
      const posY = props.event.pageY;

      // Security margin:
      const secMargin = props.margin;

      // Prevent page overflow:
      let posLeft, posTop;
      if (
        posX + menuWidth + secMargin >= winWidth &&
        posY + menuHeight + secMargin >= winHeight
      ) {
        posLeft = posX - menuWidth - secMargin;
        posTop = posY - menuHeight - secMargin;
      } else if (posX + menuWidth + secMargin >= winWidth) {
        posLeft = posX - menuWidth - secMargin;
        posTop = posY + secMargin;
      } else if (posY + menuHeight + secMargin >= winHeight) {
        posLeft = posX + secMargin;
        posTop = posY - menuHeight - secMargin;
      } else {
        posLeft = posX + secMargin;
        posTop = posY + secMargin;
      }
      if (posLeft < 0) posLeft = 0;
      if (posTop < 0) posTop = 0;

      cjuiMouseBox.value.style.left = posLeft + 'px';
      cjuiMouseBox.value.style.top = posTop + 'px';
      cjuiMouseBox.value.style.opacity = 1;

      document.addEventListener('click', closeEvent);
    }

    watch(() => props.event, () => {
      closeEvent();
      init();
    });

    return {
      cjuiMouseBox
    }
  }
};
</script>

<style lang="scss">
.cjui-mouse-box {
  min-width: 100px;
  background: #000;
  color: #fff;
  border-radius: 5px;
  box-shadow: 0 15px 35px rgba(50, 50, 90, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
  overflow: hidden;
  display: none;
  position: fixed;
  margin: 10px;
  padding: 10px;
  z-index: 2001;
  cursor: pointer;
  transition: opacity 0.4s ease-in;
}
</style>
